// pages/account/account.js
const app = getApp()

const {
  wxPost,
  wxGet,
  commonShare, serviceBusy, getJwt
} = require('../../utils/common.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    waitLoading: true,
    hasWxAuth: false, //是否授权,
    openEye:false
  },
  switchEye(){
    this.setData({openEye:!this.data.openEye})
  },
  onLoad: function(options) {
    this.refreshView = this.selectComponent("#refreshView")
    const that = this
    that.loadAssetsInfo()
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            lang: "zh_CN",
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              that.setData({
                hasWxAuth: true,
                userInfo: res.userInfo
              })
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        } else {
          that.setData({
            waitLoading: false
          }) 
          //that.checkLoginStatus()
        }
      },
      fail: function() {
        //that.checkLoginStatus()
      }
    })
  },
  loadAssetsInfo() {
    const infoId = app.globalData.subUserId ||''
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    if (app.globalData.userId && getJwt()) {
      wxGet('/assetsInfo/info', {  infoId }, ({  data }) => {
        if (data && data['errorCode'] === 0) {
          const { date: updateDate, summary, info, subAccounts, isGuest, adjustNoticeCount,subAccountNoticeAmount ,
            payNoticeAmount,reportNoticeCount,accountTitle,totalMkv} = data;
          this.setData({ updateDate, summary, info, subAccounts: subAccounts || '',
           isGuest: !!isGuest, adjustNoticeCount,payNoticeAmount,
           subAccountNoticeAmount,reportNoticeCount,accountTitle,totalMkv})
        } else if (data && data['errorCode'] === 100) {
          serviceBusy()
          this.setData({ info: {}, summary: {} })
        }
      }, null, () => {
        this.setData({
          waitLoading: false
        })
        this.refreshView.stopPullRefresh()
        wx.hideLoading()
      })
    }else{
      setTimeout(()=>{
        this.loadAssetsInfo()
      },500)
    }
  },
  loginServer() {
    app.globalData.userId = ''
    const that = this
    app.appLogin().then(function() {
      if (app.globalData.userInfo) {
        that.setData({
          userInfo: app.globalData.userInfo
        })
      }
    })
  },
  isGuest(){
    return this.data.info.id !== app.globalData.userId
  },
  bindCheck(e,url){
    const { codeBindStatus } = this.data.info || {}
    const { subAccounts } = this.data
    if (e && e.detail.userInfo) {
      if (!app.globalData.hasWxAuth) { //for update userinfo 
        app.globalData.hasWxAuth = true
        app.globalData.userInfo = e.detail.userInfo
        this.loginServer()
      }
    }
    if (!app.globalData.serviceBusy && !codeBindStatus && !this.isGuest()) {
      wx.showModal({
        title: '温馨提示',
        content: '用Code来验证身份,以便获取数据?',
        confirmText: '去验证',
        cancelText: '暂时算了',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: 'bindCode',
            })
          }
        }
      })
      return
    } else if (app.globalData.serviceBusy) {
      serviceBusy()
    } else {
      if(subAccounts && subAccounts.length){
        wx.navigateTo({
          url: `${url}?infoId=${app.globalData.subUserId||app.globalData.userId}`
        })
      } else {
        wx.navigateTo({
          url: `${url}?infoId=${app.globalData.userId}`
        })
      }
    }
  },
  comboView: function (e) {
    this.bindCheck(e, 'comboInfo/detail')
  },
  chargeView: function (e) {
    this.bindCheck(e, 'charge/profile')
  },
  adjustView: function (e) {
    this.bindCheck(e, 'adjust/list')
  },
  reportView: function (e) {
    this.bindCheck(e, 'report/list')
  },
  dealRecordImgView: function (e) {
    this.bindCheck(e, '../upload/albumList')
  },
  quitGuest:function(e){
    if(this.data.isGuest){
      const that=this
      wx.showModal({
        title: '提示',
        content: '确定要退出测试模式吗？',
        success: function (sm) {
          if (sm.confirm) {
            wx.showLoading({
              title: '退出中...',
            })
            wxPost('/assetsInfo/quitGuest', { infoId:app.globalData.userId }, ({ data }) => {
              if (data && data['errorCode'] === 0) {
                that.loadAssetsInfo()
              } else {
                wx.showToast({
                  title: data['msg'] || '删除失败',
                  icon: 'none'
                })
              }
            }, null, () => {
              wx.hideLoading()
            })
          }
        }
      })
    }else{
      wx.showToast({
        title: '当前非测试数据!',
        icon:'none',
        duration:2000
      })
    }
  },
  swtichAccount(){
    const { subAccounts } = this.data
    const that = this
    if(subAccounts && subAccounts.length){
      wx.showActionSheet({
        itemList: subAccounts.map(item=>`${item.name}${item.noticeAmount?'['+item.noticeAmount+']':''}`),
        success:function(res){
          let subUserId=subAccounts[res.tapIndex].infoId
          app.globalData.subUserId=subUserId
          that.loadAssetsInfo()
        }
      })
    }else{
      wx.showToast({
        title:'没有子账号',
        icon:'none',
        duration:2000
      })
    }
  },
  //触摸开始
  handletouchstart: function (event) {
    this.refreshView.handletouchstart(event)
  },
  //触摸移动
  handletouchmove: function (event) {
    this.refreshView.handletouchmove(event)
  },
  //触摸结束
  handletouchend: function (event) {
    this.refreshView.handletouchend(event)
  },
  //触摸取消
  handletouchcancel: function (event) {
    this.refreshView.handletouchcancel(event)
  },
  //页面滚动
  onPageScroll: function (event) {
    this.refreshView.onPageScroll(event)
  },
  onPullDownRefresh: function () {
    app.globalData.subUserId=''
    this.loadAssetsInfo()
  }
})